package com.itheima.chapter07.config;

import com.itheima.chapter07.service.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;

import javax.sql.DataSource;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private DataSource dataSource;
    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        //        // 1、基于内存的用户认证
        //        auth.inMemoryAuthentication().passwordEncoder(encoder)
        //                .withUser("shitou").password(encoder.encode("123456")).roles("common")
        //                .and()
        //                .withUser("李四").password(encoder.encode("123456")).roles("vip");

        //        // 2、使用jdbc进行身份校验
        //        String userSQL = "SELECT username, PASSWORD, valid FROM t_customer WHERE username = ?";
        //        String authoritySQL = "SELECT c.username, a.authority FROM t_customer c\n" +
        //                "LEFT JOIN t_customer_authority ca ON c.id=ca.customer_id\n" +
        //                "LEFT JOIN t_authority a ON ca.authority_id=a.id\n" +
        //                "WHERE c.username = ?";
        //        auth.jdbcAuthentication().passwordEncoder(encoder)
        //                .dataSource(dataSource)
        //                .usersByUsernameQuery(userSQL)
        //                .authoritiesByUsernameQuery(authoritySQL);

        // 3、使用UserDetailsService进行身份校验
        auth.userDetailsService(userDetailsService).passwordEncoder(encoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();

        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/login/**").permitAll()   // login下的资源文件，都放行
                .antMatchers("/detail/common/**").hasRole("common")
                .antMatchers("/detail/vip/**").hasRole("vip")
                .anyRequest().authenticated()
                .and()
                .formLogin();

        http.formLogin()
                .loginPage(("/userLogin")).permitAll()
                .usernameParameter("name").passwordParameter("pwd")
                .defaultSuccessUrl("/")
                .failureForwardUrl("/userLogin?error");

        http.logout()
                .logoutUrl("/mylogout")
                .logoutSuccessUrl("/");

        http.rememberMe()
                .rememberMeParameter("rememberme")
                .tokenValiditySeconds(200)
                .tokenRepository(tokenRepository());
    }

    @Bean
    public JdbcTokenRepositoryImpl tokenRepository() {
        JdbcTokenRepositoryImpl jr = new JdbcTokenRepositoryImpl();
        jr.setDataSource(dataSource);
        return jr;
    }
}
